//
//  SC_BarChartPlotView.m
//  SCCharts
//
//  Created by Yang on 9/9/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "SC_BarChartPlotView.h"
#import "SC_BarChartData.h"

//static float MarginHeightWithScroll  = 30.0f;

#pragma mark ChartMargin Data 

static float ChartTopMargin = 10.0f;
static float ChartBottomMargin = 30.0f;
static float ChartLeftMargin = 10.0f;
static float ChartRightMargin = 10.0f;

static float BarFrontWidth = 20.0f;
static float BarSideWidth = 5.0f;
static float BarTopHeight = 5.0f;

static float MarginBetweenBars = 4.0f;
static float MarginBetweenColumns = 20.0f;

@implementation SC_BarChartPlotView

@synthesize delegate;

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        self.backgroundColor = [UIColor clearColor];
		dataArray = [[NSMutableArray alloc] init];
		numberOfColumn = 0;
		//self.userInteractionEnabled = NO;
		
		indicator = [[SC_IndicatorView alloc] initWithFrame:CGRectMake(-200.0f, 0.0f, 80.0f, 43.0f)];
		[self addSubview:indicator];
		//[indicator setLabel:@"Test" isUp:YES];
		
		UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
		[tap addTarget:self action:@selector(tapedOnPlotView:)];
		[self addGestureRecognizer:tap];
		[tap release];
    }
    return self;
}
- (void)tapedOnPlotView:(UITapGestureRecognizer *)sender {
	
	CGPoint point = [sender locationInView:self];
	[self showIndicatorForTapPoint:point];
	//NSLog(@"tap location : x = %.0f , y = %.0f",point.x,point.y);
	//NSLog(@"taped");
}
- (void)showIndicatorForTapPoint:(CGPoint )point {
	NSInteger m,n;
	
	m = (point.x - ChartLeftMargin) / (numberOfColumn * (BarFrontWidth + BarSideWidth + MarginBetweenBars) + MarginBetweenColumns);
	float rest = (int)(point.x - ChartLeftMargin) % (int)(numberOfColumn * (BarFrontWidth + BarSideWidth + MarginBetweenBars) + MarginBetweenColumns);
	n = rest / (BarFrontWidth + BarSideWidth + MarginBetweenBars);
	if (n >= numberOfColumn) {
		n = numberOfColumn - 1;
	}
	SC_BarChartData *data = [dataArray objectAtIndex:n];
	NSString *value = [data.data objectAtIndex:m];
	
	float y = [self yForValue:[value floatValue]];
	BOOL up = NO;
	if (y < self.frame.size.height / 2) {
		up = YES;
	}
	float x = ChartLeftMargin + m *(numberOfColumn * (BarFrontWidth + BarSideWidth + MarginBetweenBars) + MarginBetweenColumns) +
	n * (BarFrontWidth + BarSideWidth + MarginBetweenBars) + (BarFrontWidth + BarSideWidth)/2;
	
	if (up) {
		y = y + indicator.frame.size.height / 2;
	}
	else {
		y = y - indicator.frame.size.height / 2;
	}
	NSString *upperString;
	switch (n) {
		case 0:
			upperString = @"总数";
			break;
		case 1:
			upperString = @"超标数";
			break;
		case 2:
			upperString = @"故障或停产数";
			break;
		default:
			break;
	}
	[indicator setUpLable:upperString lowerLabel:value isUp:up];
	indicator.center = CGPointMake(x, y);
	
	//NSLog(@"value :%@",value);
	
	
}
- (void)resetIndicator {
	indicator.center = CGPointMake(-1000.0f, -1000.0f);
}
//- (float )marginHeightWithScrollView {
//	return MarginHeightWithScroll;
//}


- (void)setData:(NSArray *)data {
	[dataArray setArray:data];
	numberOfColumn = [dataArray count];
	[self calculateDataValues];
	[self setNeedsDisplay];
}
- (void)calculateDataValues {
	NSInteger count = 0;
	for (SC_BarChartData *data in dataArray) {
		count = 0;
		for (NSString *string in data.data) {
			count ++;
			if (maxValue < [string intValue]) {
				maxValue = [string intValue];
			}
		}
	}
	int temp = maxValue;
	if (temp%3 != 0) {
		int x = maxValue / 3;
		maxValue = (x + 1) * 3;
	}
	
	float width = ChartLeftMargin + ChartRightMargin +
	(numberOfColumn * (BarFrontWidth + BarSideWidth + MarginBetweenBars) + MarginBetweenColumns) * count;
	CGRect frame = self.frame;
	frame.size.width = width;
	self.frame = frame;
	[delegate plotViewSizeChangedTo:CGSizeMake(width, frame.size.height)];
	
}
#pragma mark Drawing methods
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
	[self drawXAxisLabels:context];
	[self drawBars:context];
}
- (void)drawXAxisLabels:(CGContextRef)context {
	CGContextSetStrokeColorWithColor(context,[UIColor blackColor].CGColor);
	CGContextSetLineWidth(context, 1.0);
	CGPoint strokeSegments[] =
	{
		CGPointMake(0.0f,self.frame.size.height - ChartBottomMargin),
		CGPointMake(self.frame.size.width, self.frame.size.height - ChartBottomMargin),
	};
	CGContextStrokeLineSegments(context, strokeSegments, sizeof(strokeSegments)/sizeof(strokeSegments[0]));
	CGContextStrokePath(context);
}
- (void)drawBars:(CGContextRef )context {
	float y = self.frame.size.height - ChartBottomMargin;
	float marginBars = BarFrontWidth + BarSideWidth + MarginBetweenBars;
	float marginColumns = marginBars * numberOfColumn + MarginBetweenColumns;
	for (int i = 0; i < numberOfColumn; i ++) {
		SC_BarChartData *data = [dataArray objectAtIndex:i];
		for (int j = 0; j < data.data.count; j ++) {
			NSString *string = [data.data objectAtIndex:j];
			float x = ChartLeftMargin + i * marginBars + j * marginColumns;
			[self drawBar:context
				  atPoint:CGPointMake(x, y)
			 withPara:[NSDictionary dictionaryWithObjectsAndKeys:string,@"value",[NSNumber numberWithInt:i],@"colorType",nil]];
				 //withPara:[NSDictionary dictionaryWithObject:string forKey:@"value"]];
			
			if (i == 0) {
				NSString *title = [data.titles objectAtIndex:j];
				
				float columnWidth = marginColumns - MarginBetweenColumns - MarginBetweenBars;
				CGSize size = [title sizeWithFont:[UIFont systemFontOfSize:16.0f]];
				float x2 = x + columnWidth/2 - size.width / 2;
				float y2 = y;
				[self drawTitle:context atPoint:CGPointMake(x2, y2) withTitle:title];
				
			}
			
		}
	}
	
}
- (void)drawBar:(CGContextRef)context atPoint:(CGPoint)point withPara:(NSDictionary *)para {
	
	float value = [[para objectForKey:@"value"] floatValue];
	NSInteger colorType = [[para objectForKey:@"colorType"] intValue];
	
	UIColor *frontColor;
	UIColor *sideColor;
	UIColor *topColor;
	UIColor *boundColor;
	switch (colorType) {
		case 0:
			frontColor = [UIColor colorWithRed:251.0f/255.0f green:60.0f/255.0f blue:60.0f/255.0f alpha:1.0f];
			sideColor = [UIColor colorWithRed:197.0f/255.0f green:64.0f/255.0f blue:64.0f/255.0f alpha:1.0f];
			topColor = [UIColor colorWithRed:197.0f/255.0f green:64.0f/255.0f blue:64.0f/255.0f alpha:1.0f];
			boundColor = [UIColor redColor];
			break;
		case 1:
			frontColor = [UIColor colorWithRed:64.0f/255.0f green:64.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
			sideColor = [UIColor colorWithRed:64.0f/255.0f green:64.0f/255.0f blue:197.0f/255.0f alpha:1.0f];
			topColor = [UIColor colorWithRed:64.0f/255.0f green:64.0f/255.0f blue:197.0f/255.0f alpha:1.0f];
			boundColor = [UIColor blueColor];
			break;
		case 2:
			frontColor = [UIColor colorWithRed:64.0f/255.0f green:255.0f/255.0f blue:64.0f/255.0f alpha:1.0f];
			sideColor = [UIColor colorWithRed:64.0f/255.0f green:197.0f/255.0f blue:64.0f/255.0f alpha:1.0f];
			topColor = [UIColor colorWithRed:64.0f/255.0f green:197.0f/255.0f blue:64.0f/255.0f alpha:1.0f];
			boundColor = [UIColor greenColor];
			break;
		default:
			break;
	}
	

//	int gNumber = 0, vNumber = 0;
//	int baseGroundY = _rect.size.height - MARGIN_BOTTOM, baseGroundX = MARGIN_LEFT;
	CGPoint points[4];
	
	//UIColor *columnColor = [UIColor redColor];
	
	//CGContextSetFillColorWithColor(context, columnColor.CGColor);
	CGContextSetStrokeColorWithColor(context, boundColor.CGColor);
	
	
	
	float columnHeight = self.frame.size.height - ChartBottomMargin - [self yForValue:value] ;
	
	//画正面
	CGContextSetFillColorWithColor(context, frontColor.CGColor);
	CGContextAddRect(context, CGRectMake(point.x
										 , point.y - columnHeight 
										 , BarFrontWidth
										 , columnHeight));
	CGContextDrawPath(context, kCGPathFill);
	//NSLog(@"columnHeight:%f, (_rect.size.height - MARGIN_TOP - MARGIN_BOTTOM ):%f",columnHeight,(_rect.size.height - MARGIN_TOP - MARGIN_BOTTOM ));
	
//	if(columnHeight < 10){
//		return;
//	}
	
	//画右侧面
	CGContextSetFillColorWithColor(context, sideColor.CGColor);
	points[0] = CGPointMake(point.x + BarFrontWidth + BarSideWidth, point.y - columnHeight -BarTopHeight);
	points[1] = CGPointMake(point.x + BarFrontWidth + BarSideWidth, point.y);
	points[2] = CGPointMake(point.x + BarFrontWidth, point.y );
	points[3] = CGPointMake(point.x + BarFrontWidth, point.y - columnHeight);
	
	CGContextAddLines(context, points, 4);
	CGContextDrawPath(context, kCGPathFill);
	
	//画上面
	CGContextSetFillColorWithColor(context, topColor.CGColor);
	points[0] = CGPointMake(point.x,point.y - columnHeight);
	points[1] = CGPointMake(point.x + BarFrontWidth, point.y - columnHeight);
	points[2] = CGPointMake(point.x + BarFrontWidth + BarSideWidth, point.y - columnHeight - BarTopHeight);
	points[3] = CGPointMake(point.x + BarTopHeight,point.y - columnHeight - BarTopHeight);
	
	CGContextAddLines(context, points, 4);
	CGContextDrawPath(context, kCGPathFill);
//	
}
- (void)drawTitle:(CGContextRef )context atPoint:(CGPoint )point withTitle:(NSString *)string {
	[[UIColor blackColor] set];
	[string drawAtPoint:point withFont:[UIFont systemFontOfSize:16.0f]];
}
#pragma mark Coordinate transfer
- (float )yForValue:(float )value {
	return ChartTopMargin + (1 - value / maxValue) * (self.frame.size.height - ChartTopMargin - ChartBottomMargin);
}
- (float )valueForY:(float )y {
	return 0.0f;
}


- (void)dealloc {
	[dataArray release];
    [super dealloc];
}


@end
